import React, { useState } from 'react';
import styled from 'styled-components';

// 模态框背景
const ModalWrapper = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
`;

// 模态框内容
const ModalContent = styled.div`
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  width: 300px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease-in-out;
`;

// 按钮样式
const Button = styled.button`
  background-color: ${(props) => (props.primary ? '#4A90E2' : '#ccc')};
  color: #fff;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  width: 100%;
  transition: background-color 0.3s ease;

  &:hover {
    background-color: ${(props) => (props.primary ? '#357ABD' : '#bbb')};
  }

  &:not(:first-child) {
    margin-top: 10px;
  }
`;

// 输入框样式
const Input = styled.input`
  width: 100%;
  padding: 10px;
  margin: 10px 0;
  border-radius: 5px;
  border: 1px solid #ddd;
  font-size: 16px;
`;

// 错误提示样式
const ErrorMessage = styled.p`
  color: red;
  font-size: 14px;
  margin-top: 10px;
`;

const AddCourseModal = ({ time, day, course, onSave, closeModal }) => {
  const [courseName, setCourseName] = useState(course ? course.name : '');
  const [instructor, setInstructor] = useState(course ? course.instructor : '');
  const [startTime, setStartTime] = useState(course ? course.time : ''); // 新增开始时间
  const [endTime, setEndTime] = useState(course ? course.endTime : '');  // 新增结束时间
  const [error, setError] = useState('');

  // 保存
  const handleSubmit = () => {
    if (!courseName || !instructor || !startTime || !endTime) {
      setError('请填写完整的行程信息');
      return;
    }
    onSave(courseName, startTime, endTime, day, instructor);  // 传递开始时间和结束时间
    closeModal();  // 关闭模态框
    setError('');  // 清除错误信息
  };

  return (
    <ModalWrapper>
      <ModalContent>
        <h3>{course ? '编辑行程' : '添加行程'}</h3>
        <Input
          type="text"
          placeholder="请输入时间安排"
          value={courseName}
          onChange={(e) => setCourseName(e.target.value)}
        />
        <Input
          type="time"
          value={startTime}
          onChange={(e) => setStartTime(e.target.value)} 
        />
        <Input
          type="time"
          value={endTime}
          onChange={(e) => setEndTime(e.target.value)} 
        />
        <Input
          type="text"
          placeholder="请输入地点"
          value={instructor}
          onChange={(e) => setInstructor(e.target.value)}
        />
        
        {error && <ErrorMessage>{error}</ErrorMessage>}
        
        <Button primary onClick={handleSubmit}>保存</Button>
        <Button onClick={closeModal}>关闭</Button>
      </ModalContent>
    </ModalWrapper>
  );
};

export default AddCourseModal;
